import { ExtensionContext, commands, window, Position, Range } from "vscode"
// 插件激活时触发

function pxToRem(str: string): string {
  const arr: string[] = []
  const newStr = str.split(";")
  newStr.forEach(item => {
    const existPx = item.match(/\d*px/g)
    // 该行css存在px
    if (existPx) {
      // 存在多个px
      if (existPx.length > 1) {
        let pxStrArr = item.split(/\d*px/g)
        const dealPxStrArr: string[] = []
        existPx.forEach((subitem: any, index) => {
          dealPxStrArr.push(pxStrArr[index] + subitem.replace(subitem.match(/\d*px/g), `unit(${subitem.replace(/\D/g, "")} / @rem, rem)`))
        })
        // 按px裁剪的数组元素个数可能多于px的个数
        if (pxStrArr.length > existPx.length) {
          for (let i = existPx.length; i < pxStrArr.length; i++) {
            arr.push(dealPxStrArr.join(" ") + " " + pxStrArr[i])
          }
        } else {
          arr.push(dealPxStrArr.join(" "))
        }
        //  只存在单个px
      } else {
        arr.push(item.replace(existPx[0], `unit(${Number(item.split("px")[0].replace(/\D/g, "")).toString()} / @rem, rem)`))
      }
      // 该行css不存在px
    } else {
      arr.push(item)
    }
  })
  return arr.join(";")
}

export function activate(context: ExtensionContext) {
  let disposable = commands.registerCommand("pxrem.helloWorld", () => {
    const { activeTextEditor } = window
    // activeTextEditor!.selection 获取选中文本
    // activeTextEditor!.document.getText()  获取页面所有文本
    const currentSelect = activeTextEditor!.document.getText() // 根据范围获取选中文本
    const result = pxToRem(currentSelect)
    activeTextEditor!.edit(editBuilder => {
      const end = new Position(activeTextEditor!.document.lineCount + 1, 0)
      editBuilder.replace(new Range(new Position(0, 0), end), result)
    })
  })
  context.subscriptions.push(disposable)
}
// 插件触发
export function deactivate() {}
